package com.mystore.listener;

import com.mystore.service.GoodService;
import com.mystore.service.impl.GoodServiceImpl;
import com.mystore.util.CartUtil;
import com.mystore.vo.GoodVO;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.sql.SQLException;
import java.util.List;

@WebListener()
public class CartListener implements   HttpSessionListener {

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session create");

        GoodService goodService = new GoodServiceImpl();
        List<GoodVO> list = goodService.finAllGood();
        HttpSession session = se.getSession();
        for(GoodVO goodVO :list){
            session.setAttribute(String.valueOf(goodVO.getId()),goodVO);
        }

        System.out.println("将商品信息加载到session中");
      /* Session is created. */
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("退出session.....");
        HttpSession session = se.getSession();
        try {
            CartUtil.updateSession(session);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        System.out.println("session destoy");
      /* Session is destroyed. */
    }
}
